package com.xneure.database;

import java.sql.PreparedStatement;
import java.util.Map;
import java.util.Map.Entry;
// import org.apache.ibatis.mapping.BoundSql;
// import org.apache.ibatis.mapping.ParameterMapping;
// import org.apache.ibatis.mapping.ParameterMode;
// import java.util.List;
import java.util.Properties;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import com.xneure.utils.ObjectUtil;
import com.xneure.utils.SpringUtil;

@Intercepts(@Signature(method = "setParameters",type = ParameterHandler.class,args = {PreparedStatement.class}))
public class ParameterInterceptor implements Interceptor{
	public static boolean isInitHandler = true;

	@SuppressWarnings({"rawtypes","unchecked"})
	@Override
	public Object intercept(Invocation invocation) throws Throwable{
		if(isInitHandler){
			ParameterHandler target = (ParameterHandler)invocation.getTarget();
			TypeHandlerRegistry typeHandlerRegistry = ObjectUtil.getFieldValue(target,"typeHandlerRegistry");
			Map<String,MyBatisTypeHandler> handler = SpringUtil.getBeanByCls(MyBatisTypeHandler.class);
			if(null != handler && handler.size() > 0){
				boolean isReg;
				for(Entry<String,MyBatisTypeHandler> ent:handler.entrySet()){
					MyBatisTypeHandler _handler = ent.getValue();
					Class[] supportType = _handler.supportType();
					if(supportType != null){
						isReg = false;// 是否需要注册
						for(Class cls:supportType){
							if(_handler.isForce() || null == typeHandlerRegistry.getTypeHandler(cls)){
								isReg = true;
								break;
							}
						}
						if(isReg){
							for(Class<Object> cls:supportType){// 注册java类型
								BaseTypeHandler<Object> bean = SpringUtil.getBean(ent.getKey());
								typeHandlerRegistry.register(cls,bean);
							}
							JdbcType[] jdbcType = _handler.jdbcType();
							if(null != jdbcType){
								for(JdbcType cls:jdbcType){// 注册数据库类型
									typeHandlerRegistry.register(cls,SpringUtil.getBean(ent.getKey()));
								}
							}
						}
					}
				}
			}
			isInitHandler = false;
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target){
		if(target instanceof ParameterHandler){
			return Plugin.wrap(target,this);
		}else{
			return target;
		}
	}

	@Override
	public void setProperties(Properties arg0){
	}
}
